<?php
namespace app\api\controller;

use think\Controller;
use think\Request;

use app\api\model\Member as CM;
use app\api\model\MemberProfile;
use app\api\model\MemberInfo;
use app\api\model\MemberLevel;
use app\api\model\LoginLog;
use app\api\model\Problem;
use app\api\model\Upload;
use app\api\model\Turntable;
use app\api\model\BalanceRecord;
use app\api\model\Mentor;
use app\api\model\GoldRecord;
use app\common\model\JdWx;
use app\common\model\DuiBa;
use app\common\model\Currency;
use app\api\model\Course;
use app\api\model\CourseMenu;
use app\api\model\CourseRecord;
use app\api\model\ClassCourse;
use app\api\model\MemberClass;
use app\api\model\MemberCourseAgreement;
use app\api\model\MemberCourseNote;
use app\api\model\MemberCourseQuestion;

use app\api\validate\MemberProfileValidate;
use app\api\validate\CheckValidate;


class Member extends Common
{
    const EDIT_TYPE = [1,2,3,4,5,6]; //头像，昵称，性别，生日，地区
    
    private $noCheckAction = [];//不需要验证的方法
    
    public function initialize(){
        parent::initialize();
        $this->doCheckAuth($this->noCheckAction);
    }
    
    /**
    *   编辑用户信息
    */
    public function editProfie(){
        if(!$this->request->isPost()){
            return apiError('请求方式错误');
        }
        $request = $this->request->post();
        if(empty($request['type'])){
            return apiError('缺失参数');
        }
        $type = (int)$request['type'];
        if(!in_array($type, self::EDIT_TYPE)){
            return apiError('类型参数错误');
        }
        $validate = new MemberProfileValidate();
        $mid = $this->member->id;
        
        $profile_model = new MemberProfile;
        if($type == 2){
            if(!$validate->scene($validate::SCENE_EDIT_NICKNAME)->check($request)){
                return apiError($validate->getError());
            }
            
            
            $ret = $profile_model->_setNickName($mid,$request['nick_name']);
            if(!$ret){
                die(apiError($profile_model->getError()));
            }else{
                die(apiSuccess([],'编辑成功'));
            }
        }elseif($type == 3){
            if(!$validate->scene($validate::SCENE_EDIT_SEX)->check($request)){
                return apiError($validate->getError());
            }
            $ret = $profile_model->_setSex($mid,$request['sex']);
            if(!$ret){
                die(apiError($profile_model->getError()));
            }else{
                die(apiSuccess([],'编辑成功'));
            }
        }elseif($type == 4){
            if(!$validate->scene($validate::SCENE_EDIT_BIRTH)->check($request)){
                return apiError($validate->getError());
            }
            
            $ret = $profile_model->_setBirth($mid,$request['birth']);
            if(!$ret){
                die(apiError($profile_model->getError()));
            }else{
                die(apiSuccess([],'编辑成功'));
            }
        }elseif($type == 5){
            if(!$validate->scene($validate::SCENE_EDIT_ADDRESS)->check($request)){
                return apiError($validate->getError());
            }
            
            $pid = intval($request['pid']);
            $cid = intval($request['cid']);
            $aid = isset($request['aid']) ? intval($request['aid']) : 0;
            $ret = $profile_model->_setAddress($mid, $pid, $cid, $aid);
            
            if(!$ret){
                die(apiError($profile_model->getError()));
            }else{
                die(apiSuccess([],'编辑成功'));
            }
        }elseif($type == 1){
            if(!$validate->scene($validate::SCENE_EDIT_IMAGE)->check($request)){
                die(apiError($validate->getError()));
            }
            
            $ret = $profile_model->_setImage($mid,$request['image']);
            if(!$ret){
                die(apiError($profile_model->getError()));
            }else{
                die(apiSuccess([],'编辑成功'));
            }
        }elseif($type == 6){
            $ret = $profile_model->_setEmail($mid,$request['email']);
            if(!$ret){
                die(apiError($profile_model->getError()));
            }else{
                die(apiSuccess([],'编辑成功'));
            }
        }
        
    }
    

    
    /**
    * 获取用户信息
    */
    public function getProfile(){
        $member = $this->member;
        $isMember = $this->isMember;
        $mid = $member['id'];
        $model = new CM;
        $data = $model->_getInfoById($mid);
        
        die(apiSuccess($data));
    }
    
    /**
    * 修改密码
    */
    public function editPwd(){
        $member = $this->member;
        $mid = $member['id'];
        
        $model = new CM; 
        
        if(!$this->request->isPost()){
            return apiError('请求方式错误'); 
        }
        $request = $this->request->post();
        $request['mid'] = $mid;
        $validate = new CheckValidate();
        if(!$validate->scene($validate::SCENE_EDIT_PWD)->check($request)){
            return apiError($validate->getError());
        }
        $tel = $request['tel'];
        $pwd = $request['pwd'];
        $code = $request['code'];
        $pwd1 = $request['pwd1'];
        $member_info = $model->_editPwd($mid, $tel, $code, $pwd, $pwd1);
        if(!$member_info){
            return apiError($model->getError());
        }
        return apiSuccess([],'成功');
    }
    
    /**
    * 会员课程
    */
    public function myCourse(){
        $member = $this->member;
        $mid = $member['id'];
        $model = new MemberClass;
        $list = $model->_list(['mc.mid'=>$mid]);
        die(apiSuccess($list));
    }
    
    /**
    * 会员协议
    */
    public function myCourseAgreement(){
        $member = $this->member;
        $mid = $member['id'];
        $model = new MemberCourseAgreement;
        $list = $model->_list(['mca.mid'=>$mid]);
        die(apiSuccess($list));
    } 
    
    /**
    * 我的观看记录
    */
    public function scanRecord(){
        $member = $this->member;
        $mid = $member['id'];
        $model = new CourseRecord;
        $list = $model->_scanRecord($mid);
        die(apiSuccess($list));
    }
    
    /**
    * 创建设备日志
    */
    public function addEquipmentLog(){
        if(!$this->request->isPost()){
            die(apiError('请求方式错误'));
        }
        $member = $this->member;
        $mid = $member['mid'];
        $udid = $member['udid'];
        $request = $this->request->post();
        $isMember = $this->isMember;
        $model = new LoginLog;
        $is_tourist = -1;
        if($isMember){
            $is_tourist = 1;
        }
        $ret = $model->_addLog($mid, $udid, $is_tourist,$request);
        
        if(!$ret){
            die(apiError($model->getError()));
        }else{
            die(apiSuccess([],'创建成功'));
        }
    }
    
    /**
    * 常见问题列表
    */
     public function problemList(){
        if(!$this->request->isPost()){
            die(apiError('请求方式错误'));
        }
        
        $request = $this->request->post();
        $model = new Problem;
        $list = $model->_list();
        die(apiSuccess($list));
    }
    
    /**
    * 常见问题内容
    */
     public function problemDetail(){
        if(!$this->request->isPost()){
            die(apiError('请求方式错误'));
        }
        
        $request = $this->request->post();
        if(empty($request['id'])){
             die(apiError('问题ID缺失'));
        }
        $id = (int)$request['id'];
        $model = new Problem;
        $res = $model->_getProblemById($id);
        if(!$res){
            die(apiError($model->getError()));
        }else{
            die(apiSuccess($res));
        }
    }
    
    /**
    * 获取系统配置文件
    */
    public function getSysConfig(){
        $sys = $this->sysconfig;
        die(apiSuccess($sys));
    }
    
    /**
    * 服务协议
    */
     public function getAgreement(){
        $request = $this->request->post();
        if(empty($request['id'])){
            die(apiError('协议id缺失'));
        }
        $id = (int)$request['id'];

        $member = $this->member;
        $mid = $member['id'];

        $model = new MemberClass;
        $ret = $model->_signAgreement($mid, $id);
        if(!$ret){
            die(apiError($model->getError()));
        }
        
        die(apiSuccess([], '签署成功'));
    }
    
    /**
    * 我的协议详情
    */
    public function myAgreementDetail(){
        $request = $this->request->post();
        if(empty($request['id'])){
            die(apiError('协议id缺失'));
        }
        $id = (int)$request['id'];
        $model = new MemberCourseAgreement;
        $agree = $model->_getInfoByID($id);
        if(empty($agree)){
            die(apiError('该协议不存在'));
        }

        die(apiSuccess($agree));
    }
    
    /**
    *获取班级的所有课程
    */
    public function getAllCourse(){
        $request = $this->request->post();
        $model = new MemberClass;
        $member = $this->member;
        $request['mid'] = $member['id'];
        $list = $model->_getAllCourse($request);
        die(apiSuccess($list));
    }
    
    
    /**
    * 收徒规则
    */
     public function apprenticeRule(){
        $sys = $this->sysconfig;
        die(apiSuccess(['content'=>$sys['APPRENTICE_RULE']]));
    }


    /**
    * 会员上传头像
    */
    public function uploadHead(){
        $model = new Upload;
        $variable = 'image';
        $controller = $this->request->controller();
        $controller = strtolower($controller);
        $dir = $controller."/"."image/head/".date("Ymd")."/".date("YmdHis").mt_rand(1000000,9999999);
        $res = $model->_uploadFile($variable, $dir);
        if(!$res){
            die(apiError($model->getError()));
        }else{
            die(apiSuccess(['img'=>$res]));
        }
    }
    
    /**
    * 更新设备ID
    */
    public function updateDeviceID(){
        $model = new CM;
        $request = $this->request->post();
        $member = $this->member;
        $mid = $member['id'];
        $device_id = $request['device_id'];
        $ret = $model->_updateDeviceID($mid, $device_id);
        if(!$ret){
            die(apiError($model->getError()));
        }else{
            die(apiSuccess([],'设备号更新成功'));
        }
    }
    
    
    /**
    * 收徒
    */
    public function bindRelation(){
        $request = $this->request->post();
        $model = new CM;
        $member = $this->member;
        
        $ret = $model->_bindRelation($member['id'], $request, $this->sysconfig);
        if(!$ret){
             die(apiError($model->getError()));
        }
        die(apiSuccess($ret,'收徒成功'));
    }
    
    /**
    * 抽奖
    */
    public function draw(){
        $member = $this->member;
        $mid = $member['id'];
        $model = new Turntable;
        $ret = $model->_draw($mid);
        if(!$ret){
            die(apiError($model->getError()));
        }
        
        if($ret['info'] == '谢谢惠顾' || $ret['info'] == '再接再厉'){
            die(apiSuccess($ret,'抽奖失败'));
        }else{
            die(apiSuccess($ret,'抽奖成功'));
        }
        
    }
    
    /**
    * 转盘列表
    */
    public function getAwards(){
        $model = new Turntable();
        $list = $model->_getAwards();
        die(apiSuccess($list));
    }
    

    /**
    * 实名认证
    */
    public function verifyRealName(){
        //var_dump(long2ip(ip2long(get_ip())));die;
        $member = $this->member;
        $mid = $member['id'];
        if($member['is_real_name'] == 1){
            die(apiSuccess('身份已验证'));
        }
        $request = $this->request->post();
        if(empty($request['name'])){
            die(apiError('请输入真实姓名'));
        }elseif(empty($request['code'])){
            die(apiError('请输入身份号'));
        }
        
        $realName = $request['name'];
        $IDCrad = $request['code'];
        //姓名正则
        $reg = "/^[a-zA-Z0-9\x{4e00}-\x{9fa5}]+$|^[a-zA-Z0-9\x{4e00}-\x{9fa5}][a-zA-Z0-9_\s\ \x{4e00}-\x{9fa5}\.]*[a-zA-Z0-9\x{4e00}-\x{9fa5}]+$/u";
         if(!preg_match($reg, $IDCrad)){
            die(apiError('请输入合法的姓名'));
        }
        //身份证正则
        $reg = "/(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/";
        if(!preg_match($reg, $IDCrad)){
            die(apiError('请输入合法的身份证号'));
        }
        
        $obj = new JdWx();
        $ret = $obj->_verifyName($realName, $IDCrad);
        if(!$ret){
            die(apiError('身份验证失败'));
        }else{
            //需要更新用户信息
            $model = new CM;
            $ret = $model->_updateRealName($mid, $realName);
            if(!$ret){
                die(apiError($model->getError()));
            }
            die(apiSuccess([], '验证成功'));
        }
    }
    
    /**
    * 我的徒弟
    */
    public function myApprentice(){
        $member = $this->member;
        $mid = $member['id'];
        $model = new Mentor;
        $list =  $model->_getApprenticeAll($mid);
        $config = $this->sysconfig ;
        $max = $config['ONE_APPRENTICE_MAX'];
        foreach($list as $k=>$v){
            $list[$k]['max'] = $max;
            $list[$k]['progress'] = intval($v['profit']/$max * 100);
        }
        
        die(apiSuccess($list));
    }
    
    /**
    * 收徒收益明细
    */
    public function myApprenticeIncomeList(){
        $member = $this->member;
        $mid = $member['id'];
        $model = new BalanceRecord;
        $list =  $model->_apprenticeIncomeList($mid);
        die(apiSuccess($list));
    }
    
    
    /**
    * 申请提现
    */
    public function applyWithdraw(){
        $member = $this->member;
        $mid = $member['id'];
        $udid = $member['udid'];
        $model = new MemberInfo;
        $config = $this->sysconfig;
        $max = $config['VERIFY_NAME_MAX'];
        
        $ret = $model->_checkIsVerifyRealname($mid, $max);
        if(!$ret){
            $member = $this->member;
            if($member['is_real_name'] != 1){
                die(apiError('需要实名认证', 701));
            }
        }
        
        $request = $this->request->post();
        
        if(empty($request['type'])){
            die(apiError('请选择提现类型'));
        }
        if(empty($request['p'])){
            die(apiError('请选择提现金额'));
        }
        $type = (int)$request['type'];
        if($type == 1){
            if($member['is_ali'] != 1){
                die(apiError('请绑定支付宝', 3001));
            }
        }elseif($type == 2){
            if($member['is_ali'] != 1){
                die(apiError('请绑定微信', 3002));
            }
        }
        
        $money = (float)$request['p'];
        $money = sprintf("%.2f",$money);
        
        if($money > $member['balance']){
            die(apiError('余额不足'));
        }
        
        if($money <= 0){
            die(apiError('请输入合法的金额'));
        }
        $model = new CM;
        $ret = $model->_applyWithdraw($mid, $udid, $money, $type);
        if(!$ret){
            die(apiError($model->getError()));
        }
        
        die(apiSuccess([],'提现申请成功'));
    }
    
    /**
    * 绑定支付宝
    */
    public function bindAli(){
        $request = $this->request->post();
        $member = $this->member;
        $mid = $member['id'];
        if(empty($request['account'])){
            die(apiError('请输入支付宝账号'));
        }
        if(empty($request['name'])){
            die(apiError('请输入支付宝认证姓名'));
        }
        $account = filterXss($request['account']);
        $name = filterXss($request['name']);
        $model = new CM;
        $ret = $model->_bindAli($mid, $account, $name);
        if(!$ret){
            die(apiError($model->getError()));
        }
        die(apiSuccess([], '支付宝绑定成功'));
    }
    
    
    /**
    * 我的余额
    */
    public function myBalance(){
        $request = $this->request->post();
        $member = $this->member;
        $mid = $member['id'];
        if(!isset($request['type'])){
            die(apiError('请选择类型'));
        }
        $type = $request['type'];
        if(!in_array($type, [0,1,2,3])){ //0全部 1试玩，2收徒，3提现
            die(apiError('选择参数错误'));
        }
        $where = [
            ['mid', '=', $mid]
        ];
        if($type == 1){
            $where = [
                ['mid', '=', $mid],
                ['type_id', '=', 1],
            ];
        }elseif($type == 2){
            $where = [
                ['mid', '=', $mid],
                ['type_id', 'in', [2,3]],
            ];
        }elseif($type == 3){
            $where = [
                ['mid', '=', $mid],
                ['type_id', '=', 4],
            ];
        }
        $model = new BalanceRecord;
        $list = $model->_list($where);
        die(apiSuccess($list));
    }

    /**
    * 我的金币
    */
    public function myGold(){
        $request = $this->request->post();
        $member = $this->member;
        $mid = $member['id'];
        if(!isset($request['type'])){
            die(apiError('请选择类型'));
        }
        $type = $request['type'];
        if(!in_array($type, [0,1,2,3])){ //0全部 1获奖记录，2兑换记录
            die(apiError('选择参数错误'));
        }
        $where = [
            ['mid', '=', $mid]
        ];
        if($type == 1){
            $where = [
                ['mid', '=', $mid],
                ['type_id', 'in', [1,2,3,4]],
            ];
        }elseif($type == 2){
            $where = [
                ['mid', '=', $mid],
                ['type_id', '=', 5],
            ];
        }
        $model = new GoldRecord;
        $list = $model->_list($where);
        die(apiSuccess($list));
    }
    
    /**
    *   会员等级
    */
    public function memberLevelList(){
        $model = new MemberLevel;
        $list = $model->_list();
        $member = $this->member;
        $mid = $member['id'];
        $level_id = $member['level_id'];
        
        $model = new MemberLevel;
        $level = $model->_getById($level_id);
        
        $next = $model->_getNextLevel($level_id);
        
        $total_balance = $member['total_balance'];
        $next_bancle = $next['balance'] - $total_balance < 0 ? 0 : $next['balance'] - $total_balance;
        
        $model = new GoldRecord;
        $isReceive = $model->_isReceive($mid, 4);
        
        $data = [
            'progress_bar'=> (int)(($total_balance/$next['gold'])*100),
            'image'=> $level['image'],
            'level_name'=> $level['title'],
            'gold' => $level['gold'],
            'next_bancle' => $next_bancle,
            'next_name'=> $next['title'],
            'next_gold'=> $next['gold'],
            'isReceive'=> (int)!$isReceive,
            'level_list' => $list,
        ];
        
        die(apiSuccess($data));
    }
    
    
   /**
    * 会员自动升级
    */
    public function upgradeMember(){
        $member = $this->member;
        $mid = $member['id'];
        $model = new Currency;
        $ret = $model->_memberUpgrade($mid);
        if(!$ret){
            die(apiError($model->getError()));
        }
        
        die(apiSuccess());
    }
    
    
    /**
    * 会员领取每日金币
    */
    public function receiveOneDayGold(){
        $member = $this->member;
        $model = new GoldRecord;
        $ret = $model->_receiveOneDayGold($member['id'], $member['udid'], $member['level_id']);
        
        if(!$ret){
            die(apiError($model->getError()));
        }
        
        die(apiSuccess([], '领取成功'));
    }
    
    /**
    * 会员注销
    */
    public function cancellation(){
        $member = $this->member;
        $mid = $member['id'];
        $model = new CM;
        $ret = $model->_cancellation($mid);
        if(!$ret){
            die(apiError($model->getError()));
        }
        
        die(apiSuccess());
    }
    
    /**
    * 做笔记
    */
    public function courseNote(){
        $request = $this->request->post();
        if(empty($request['content'])){
            die(apiError('请输入内容'));
        }
        if(empty($request['cmid'])){
            die(apiError('章节ID缺失'));
        }
        if(empty($request['cm_time'])){
            die(apiError('时间必须'));
        }
        $cmid = (int)$request['cmid'];
        
        $model = new CourseMenu;
        $courseMenu = $model->_getInfoByID($cmid);
        if(empty($courseMenu)){
            die(apiError('参数错误'));
        }
        $cid = $courseMenu['cid'];
        
        $member = $this->member;
        $mid = $member['id'];
        
        $data['mid'] = $mid;
        $data['cid'] = $cid;
        $data['cmid'] = $request['cmid'];
        $data['cm_time'] = $request['cm_time'];
        $data['content'] = $request['content'];
        $data['created'] = time();
        
        $model = new MemberCourseNote;
        $ret = $model->_create($data);
        if(!$ret){
            die(apiError($model->getError()));
        }
        die(apiSuccess([], '提交成功'));
    }
    
    /**
    * 提问
    */
    public function addQuestion(){
        $request = $this->request->post();
        $request = $this->request->post();

        if(empty($request['cmid'])){
            die(apiError('章节ID缺失'));
        }

        $cmid = (int)$request['cmid'];
        
        $model = new CourseMenu;
        $courseMenu = $model->_getInfoByID($cmid);
        if(empty($courseMenu)){
            die(apiError('参数错误'));
        }
        $cid = $courseMenu['cid'];
        
        $member = $this->member;
        $mid = $member['id'];
        $data = $request;
        $data['cid'] = $cid;
        $data['mid'] = $mid;
        $model = new MemberCourseQuestion;
        $ret = $model->_create($data);
        if(!$ret){
            die(apiError($model->getError()));
        }
        die(apiSuccess([], '提交成功'));
    }
    /**
    *   记录课程观看
    */
    public function recordCourse(){
        $request = $this->request->post();
    }
}
